//
//  APCoinShopController.m
//  AqualPolo
//
//  Created by dong on 2024/5/9.
//

#import "APCoinShopController.h"
#import "APGoodsModel.h"
#import "APGoodsViewCell.h"
#import "APLoginManager.h"
#import "APIAPManager.h"
@interface APCoinShopController ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UILabel *coinLabel;

@end

@implementation APCoinShopController

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 25;
        layout.minimumInteritemSpacing = 15;
        layout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = UIColor.clearColor;
        [_collectionView registerClass:[APGoodsViewCell class] forCellWithReuseIdentifier:@"item"];
    }
    return _collectionView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadNaviBar2];
    self.naviBar.titleLabel.text = @"Coin Shop";
    [self initUI];
    [self requestDataList];
    [self refreshData];
    [APLogManager statisticWithPage:APPage_purchase];
}

- (void)refreshData{
    APUserModel *userModel = [[APLoginManager shareInstance] userInfo];
    _coinLabel.text = [NSString stringWithFormat:@"%zd",userModel.availableCoins];
    if (_autoBack) {
        if (self.navigationController != nil) {
            [self.navigationController popViewControllerAnimated:true];
        }else{
            [self dismissViewControllerAnimated:true completion:nil];
        }
    }

}

- (void)requestDataList{
    [self.view ShowProgress];
    NSDictionary *parameters = @{@"isIncludeSubscription": @false,@"payChannel": @"IAP"};
    [APDataManager postJsonWithUrlString:coinGoodsSearch timeoutInterval:0 parameters:parameters result:^(NSDictionary * _Nullable res) {
        [self.view removeProgress];
        if ([res[@"data"] isKindOfClass:[NSArray class]]) {
            for (NSDictionary *dict in res[@"data"]) {
                APGoodsModel *model = [APGoodsModel yy_modelWithDictionary:dict];
                [self.dataArray addObject:model];
            }
        }
        [self.collectionView reloadData];
    } failBlock:^(NSString * _Nullable errorMsg) {
        [self.view ShowProgressOnlyLabel:errorMsg];
    }];

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat width =( collectionView.frame.size.width - 55) * 0.5;
    return CGSizeMake(width, 160);
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    APGoodsViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    if (self.dataArray.count > indexPath.item) {
        APGoodsModel *model = [self.dataArray objectAtIndex:indexPath.item];
        NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle],NSStrikethroughColorAttributeName:LYRGBAColor(255, 255, 255, 0.3)};
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"$%.2f",model.originalPrice] attributes:attribtDic];
        cell.priceLabel.attributedText = attribtStr;
        cell.discountPriceLabel.text = [NSString stringWithFormat:@"$%.2f",model.price];
        cell.coinLabel.text = [NSString stringWithFormat:@"%zd",model.exchangeCoin];
        if (model.tags && model.tags.length > 0) {
            cell.tagLabel.text = model.tags;
            cell.bigDealImageView.hidden = false;
        }else{
            cell.bigDealImageView.hidden = true;
        }
        if (model.discount && model.discount > 0) {
            cell.discountLabel.text = [NSString stringWithFormat:@"%d%% off",(int)(model.discount * 100)];
            cell.discountLabel.hidden = false;
        }else{
            cell.discountLabel.hidden = true;
        }
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    APGoodsModel *model = [self.dataArray objectAtIndex:indexPath.item];
    [self createOrder:model];
}


- (void)createOrder:(APGoodsModel *)model{
    UIView *toastView = UIApplication.sharedApplication.keyWindow;
    [toastView ShowProgress];
    NSDictionary  *parameters = @{
            @"entry": @"",
            @"source": @"",
            @"payChannel": @"IAP",
            @"goodsCode": model.code
          };
    LYLog(@"===APGoodsModel==code========%@",model.code);
    [APDataManager postJsonWithUrlString:rechargeCreate timeoutInterval:0 parameters:parameters result:^(NSDictionary * _Nullable res) {
        NSString *orderNo = [res[@"data"][@"orderNo"] description];
        [[APIAPManager sharedInstance] requestProductsId:model.code success:^(NSString * _Nonnull receiptStr, NSString * _Nonnull transactionIdentifier) {
            [toastView removeProgress];
            [self requestCheckPayment:orderNo payload:receiptStr transactionId:transactionIdentifier];
        } fail:^(NSString * _Nonnull errorMsg) {
            [toastView ShowProgressOnlyLabel:errorMsg];
        }];
        
    } failBlock:^(NSString * _Nullable errorMsg) {
        [toastView ShowProgressOnlyLabel:errorMsg];
    }];
    [APLogManager statisticWithPage:APPage_createOrder];
}


- (void)requestCheckPayment:(NSString *)orderNo payload:(NSString *)payload transactionId:(NSString *)transactionId{
    UIView *toastView = UIApplication.sharedApplication.keyWindow;
    [toastView ShowProgress];
    WS(ws);
    NSDictionary *parameters =  @{@"orderNo": orderNo,@"payload": payload,@"transactionId": transactionId,@"type": @"1"};
    [APDataManager postJsonWithUrlString:checkPayment timeoutInterval:0 parameters:parameters result:^(NSDictionary * _Nullable res) {
        [[APLoginManager shareInstance] updateUserInfoByInternetSevice:^(_Bool success, NSString * _Nonnull msg) {
            [ws refreshData];
            [toastView removeProgress];
        }];
    } failBlock:^(NSString * _Nullable errorMsg) {
        [toastView ShowProgressOnlyLabel:errorMsg];
    }];
}




- (void)initUI{
    UIImageView *topImageView = [[UIImageView alloc] init];
    topImageView.image = [UIImage imageNamed:@"coin_top_bg"];
    [self.view addSubview:topImageView];
    [topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.naviBar.mas_bottom).offset(10);
        make.left.equalTo(self.view).offset(22);
        make.right.equalTo(self.view).offset(-22);
        make.height.equalTo(topImageView.mas_width).multipliedBy(107.0 / 331.0);
    }];
    
    UIImageView *coinImageView = [[UIImageView alloc] init];
    coinImageView.image = [UIImage imageNamed:@"coin_icon_big"];
    [topImageView addSubview:coinImageView];
    [coinImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(topImageView.mas_left).offset(44);
        make.centerY.equalTo(topImageView);
        make.size.mas_equalTo(CGSizeMake(61, 66));
    }];
    
    UILabel *coinTitleLabel = [[UILabel alloc] init];
    coinTitleLabel.textColor = LYRGBAColor(255, 255, 255, 0.8);
    coinTitleLabel.font = [LYFont fontWithSize:16 fontName:LYFontNamepfr];
    coinTitleLabel.textAlignment = NSTextAlignmentLeft;
    coinTitleLabel.text = @"My Coins";
    [topImageView addSubview:coinTitleLabel];
    [coinTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(coinImageView.mas_top);
        make.left.equalTo(coinImageView.mas_right).offset(11);
    }];
    _coinLabel = [[UILabel alloc] init];
    _coinLabel.textColor = [UIColor whiteColor];
    _coinLabel.font = [LYFont fontWithSize:26 fontName:LYFontNamepfb];
    _coinLabel.textAlignment = NSTextAlignmentLeft;
    [topImageView addSubview:_coinLabel];
    [_coinLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(coinTitleLabel.mas_bottom).offset(8);
        make.left.equalTo(coinImageView.mas_right).offset(11);
        make.right.equalTo(topImageView);
    }];
    
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topImageView.mas_bottom).offset(20);
        make.left.right.bottom.equalTo(self.view);
    }];
    
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    }
    return self;
}
@end
